package com.xiaotu.code.service.upload;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.xiaotu.code.util.FileUtil;

/**
 * 上传文件service.
 * @author chenxiangrong
 *
 */
public class FileUploadServiceImpl implements FileUploadService {
	protected final Logger logger = LoggerFactory.getLogger(getClass());
	private String fileRoot;//文件系统根路径

	/**
	 * 读写文件.
	 */
	@Override
	public String writeFile(String baseDir, String fileName, File fileData)
			throws IOException {
		logger.debug("进入文件读写...");
		String realPath = getFileRoot();
		String filePath = realPath + "/" + baseDir;
		String suffix = FileUtil.getFileSuffix(fileName);
		filePath = writeUniqueFile(fileData, filePath, suffix);
		return filePath;
	}
	/**
	 * 读写文件.
	 * @param fileData
	 * @param filePath
	 * @param suffix
	 * @return
	 * @throws IOException
	 */
	private String writeUniqueFile(File fileData, String filePath, String suffix) throws IOException{
		String[] fileDir=FileUtil.generateDirAndNameByUUID(suffix);
		filePath = filePath + fileDir[0] + fileDir[1];
		logger.debug("文件写入目录:"+filePath);
		File file=new File(filePath);
		// 目录是否存在
		File parentFile = file.getParentFile();
		if (!parentFile.exists()) {
			parentFile.mkdirs();
		}
		logger.debug("开始读写文件...");
		FileOutputStream fos = new FileOutputStream(filePath);
		FileInputStream fis = new FileInputStream(fileData);
		byte[] buffer = new byte[1024];
		int len = 0;
		while ((len = fis.read(buffer)) > 0) {
			fos.write(buffer, 0, len);
		}
		fos.close();
		fis.close();
		return filePath;
	}
	

	public String getFileRoot() {
		return fileRoot;
	}

	public void setFileRoot(String fileRoot) {
		this.fileRoot = fileRoot;
	}
}
